package com.baoai.service;

import com.baoai.dto.APIResponse;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;

/**
 * 用于日志打印
 * Created by xiaren on 2017/4/24.
 */
@Component
@Aspect
public class LoggerAop {

    private static final Logger LOGGER = Logger.getLogger(LoggerAop.class);

    @Pointcut("execution(* com.baoai.controller..*(..))")
    public void aspect(){	}

    @Around("aspect()")
    public Object around(JoinPoint joinPoint){
        LOGGER.info("访问: " + joinPoint.getSignature().toString());
        Object[] args = joinPoint.getArgs();
        StringBuffer sb = new StringBuffer();
        for (Object obj : args){
            sb.append("【").append(obj).append("】");
        }
        LOGGER.info("参数: " + sb);
        Object obj = null;
        try {
            obj = ((ProceedingJoinPoint) joinPoint).proceed();
            LOGGER.info("返回: " + obj);
        } catch (Throwable throwable) {
            LOGGER.error(exception(throwable));
            APIResponse apiResponse = new APIResponse();
            apiResponse.setStatus(APIResponse.FAIL);
            apiResponse.setMessage(throwable.getMessage());
            obj = apiResponse;
        }
        return obj;
    }

    /**
     * 将异常信息转化成字符串
     * @param t
     * @return
     * @throws IOException
     */
    private static String exception(Throwable t) {
        if(t == null)
            return null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        t.printStackTrace(new PrintStream(baos));
        return baos.toString();
    }
}
